<template>
  <div class="app-container customer-div">
    <el-menu :default-active="radio1" class="el-menu-demo" mode="horizontal" @select="changeRadio1">
      <el-menu-item index="1">已开票</el-menu-item>
      <el-menu-item index="2">未开票</el-menu-item>
    </el-menu>

    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
        <el-form-item label="客户编号：">
          <el-input v-model="listQuery.customerNumber" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称：">
          <el-autocomplete
            clearable
            class="inline-input"
            value-key="customerName"
            :fetch-suggestions="querySearch"
            v-model="listQuery.customerName"
            placeholder="请输入内容"
            @select="handleSelectCustomerName"
            :trigger-on-focus="false"
            @clear="listQuery.customerId=''"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="订单号：">
          <el-input v-model="listQuery.orderSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="业务员：" >
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="(item,index) in userOptionList"
              :key="index"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="发票号：" v-if="radio1 == 1">
          <el-input v-model="listQuery.invoiceNo" clearable></el-input>
        </el-form-item>

        <el-form-item label="牌号：">
          <el-select
            clearable
            v-model="listQuery.goodsSn"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :loading="loading"
            :remote-method="remoteMethod">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item.goodsSn"
              :value="item.goodsSn">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开票日期：" v-if="radio1 == 1">
          <el-date-picker
            v-model="listQuery.invoiceDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="订单日期" v-if="radio1 == 2">
          <el-date-picker
            v-model="listQuery.createDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
            v-if="exportSaleInvoice && listQuery.tab != 'my' && radio1 == 1 "
            :loading="btnloading"
            @click="downloadExcel()">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div style="font-size:14px;line-height: 30px;padding:10px 0 ">
      <el-radio-group v-model="listQuery.tab" @change="handleSelect" size="small">
        <el-radio-button label="my">我的</el-radio-button>
        <el-radio-button label="department" v-if="departmentSaleInvoice">部门</el-radio-button>
        <el-radio-button label="all" v-if="allSaleInvoice">全部</el-radio-button>
      </el-radio-group>
      <span v-if="radio1 == 1">
        <span style="padding-left:20px;">已开票：</span><span style="font-weight: bold">{{summary.hasInvoiceAmount}}</span>
        <span><span style="padding-left:20px;">发票数量：</span><span style="font-weight: bold">{{summary.invoiceNum}}</span></span>
      </span>
      <span v-else-if="radio1 == 2">
        <span style="padding-left:20px;" >未开票金额：</span><span style="font-weight: bold">{{unInvoiceAmount}}</span>
        <span style="padding-left:20px;" >未开票数量：</span><span style="font-weight: bold">{{unInvoiceGoodsNum}}</span>
      </span>

    </div>

    <div class="table-container">
      <el-table
        v-if="radio1 == 1"
        v-loading="listLoading"
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column  label="订单号" width="250" prop="orderSn" align="center">
          <template slot-scope="scope">
            <div>
              <el-link @click="toDetail(scope.row)" type="primary" style="font-size:12px;vertical-align: middle">
                {{scope.row.orderSn}}
              </el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="客户编号"
          width="300">
          <template slot-scope="scope">
            <span>
                {{scope.row.customerNumber }}
              </span>
            <!--是否有权限-->
            <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="业务员"
          width="100">
          <template slot-scope="scope">
            {{scope.row.userName }}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderAmount"
          label="订单金额"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="hasInvoiceAmount"
          label="已开票金额"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="unInvoiceAmount"
          label="未开票金额"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="goodsNum"
          label="合同数量"
          width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="goodsSendNum"
          label="已发货数量"
          width="100"
          align="center">
        </el-table-column>

        <el-table-column
          class-name="cspantd"
          label="牌号"
          width="200"
          align="center">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.invoiceList" :style="{'border-bottom': index==scope.row.invoiceList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
              {{item.goodsSn}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="开票数量"
          width="100"
          align="center">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.invoiceList" :style="{'border-bottom': index==scope.row.invoiceList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
              {{item.goodsNum}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="发票金额"
          width="100"
          align="center">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.invoiceList" :style="{'border-bottom': index==scope.row.invoiceList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
              {{item.goodsAmount}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="开票日期"
          width="100"
          align="center">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.invoiceList" :style="{'border-bottom': index==scope.row.invoiceList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
              {{item.invoiceDate}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="发票号"
          width="200"
          align="center">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.invoiceList" :style="{'border-bottom': index==scope.row.invoiceList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
              {{item.invoiceSn}}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          width="150"
          fixed="right"
          label="操作"
          class-name="cspantd"
          align="center">
          <template slot-scope="scope">
            <div class="tdDiv" v-for="(item,index) in scope.row.invoiceList" :style="{'border-bottom': index==scope.row.invoiceList.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5'}">
              <el-button
                v-if="item.invoiceFile"
                type="text"
                size="mini"
                @click="toPdf(item.invoiceFile)">下载发票
              </el-button>
              <span v-else>--</span>
            </div>

          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-else-if="radio1 == 2"
        v-loading="listLoading"
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column  label="订单号" min-width="250" prop="orderSn" align="center">
          <template slot-scope="scope">
            <div>
              <el-link @click="toDetail(scope.row)" type="primary" style="font-size:12px;vertical-align: middle">
                {{scope.row.orderSn}}
              </el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="客户编号"
          min-width="300">
          <template slot-scope="scope">
            <span>
                {{scope.row.customerNumber }}
              </span>
            <!--是否有权限-->
            <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="业务员"
          min-width="100">
          <template slot-scope="scope">
            {{scope.row.userName }}
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsAmount"
          label="订单金额"
          min-width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="goodsInvoiceAmount"
          label="已开票金额"
          min-width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="unInvoiceAmount"
          label="未开票金额"
          min-width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="goodsNum"
          label="合同数量"
          min-width="100"
          align="center">
        </el-table-column>
        <el-table-column
          prop="goodsSendNum"
          label="已发货数量"
          min-width="100"
          align="center">
        </el-table-column>

        <el-table-column
          class-name="cspantd"
          label="牌号"
          min-width="200"
          align="center">
          <template slot-scope="scope">
            {{scope.row.goodsSn}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="已开票数量"
          min-width="100"
          align="center">
          <template slot-scope="scope">
             {{scope.row.goodsInvoiceNum}}
          </template>
        </el-table-column>
        <el-table-column
          class-name="cspantd"
          label="未开票数量"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.unInvoiceGoodsNum}}
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>


  </div>
</template>
<script>
  import {getCustomerOption,getOrderUsersList} from '@/api/partner'
  import {goodsList,invoiceListNew,invoiceExportNew,unInvoiceList} from '@/api/company'
  import {formatDate} from '@/utils/date';
  import store from '@/store'
  import { mapGetters } from 'vuex'
  const defaultListQuery={
    "pageNum": 1,
    "pageSize": 10,
    "customerId": "", //客户ID
    "customerNumber": "", //客户编码
    "orderSn": "", //订单号
    "userId": "", //业务员ID
    "invoiceNo": "", //发票号
    "goodsSn": "", //牌号
    "invoiceDate": [], //开票日期
    "tab": "my", //my-我的，department-部门，all-全部
    createDate:[]
  };
  export default {
    name: "index",
    data(){
      return {
        listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
        tableData: [],
        listLoading: false,
        userOptionList:[],
        roles:store.getters.roles ? store.getters.roles : [],
        loading:false,
        options:[],
        btnloading:false,
        count:0,
        summary:{},
        radio1:'1',
        unInvoiceAmount : 0,
        unInvoiceGoodsNum :0
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'mobile',
        'userId',
        'isMange',
      ]),
      exportSaleInvoice(){
        if(this.roles.indexOf("exportSaleInvoice") != -1){
          return true
        }else{
          return false
        }
      },
      allSaleInvoice(){
        if(this.roles.indexOf("allSaleInvoice") != -1){
          return true
        }else{
          return false
        }
      },
      departmentSaleInvoice(){
        if(this.roles.indexOf("departmentSaleInvoice") != -1){
          return true
        }else{
          return false
        }
      }
    },
    created() {
      let now = new Date();
      let nowMonth = now.getMonth(); //当前月
      let nowYear = now.getFullYear(); //当前年
      //本月的开始时间
      let monthStartDate = new Date(nowYear, nowMonth, 1);
      //本月的结束时间
      let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
      let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
      let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
      this.listQuery.invoiceDate = [startDate,endDate]
      if(this.$route.query.tab){
        this.listQuery.tab = this.$route.query.tab
      }
      this.getList();
      this.getUserOptionList();
    },
    filters: {

    },
    methods:{
      changeRadio1(key){
        this.radio1 = key
        let now = new Date();
        let nowMonth = now.getMonth(); //当前月
        let nowYear = now.getFullYear(); //当前年
        //本月的开始时间
        let monthStartDate = new Date(nowYear, nowMonth, 1);
        //本月的结束时间
        let monthEndDate = new Date(nowYear, nowMonth+1, 0,23,59,59);
        let startDate = formatDate(monthStartDate, 'yyyy-MM-dd');
        let endDate = formatDate(monthEndDate, 'yyyy-MM-dd');
        this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
        if(this.radio1 == 2){
          this.listQuery.createDate = [startDate,endDate]
        }else if(this.radio1 == 1){
          this.listQuery.invoiceDate = [startDate,endDate]
        }
        this.handleSearchList();
      },
      toPdf(url){
        if(url){
          window.open(url)
        }else{
          this.$message.warning('无发票文件')
        }
      },

      //下载excle
      downloadExcel(){
        let params = JSON.parse(JSON.stringify(this.listQuery));
        this.btnloading = true;
        invoiceExportNew(params).then((res)=>{
          this.btnloading = false;
          require.ensure([], () => {
            const { export_json_to_excel } = require('sheet/Export2Excel');
            const tHeader = res.title;
            const filterVal = res.columns;
            const list = res.list;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, res.fileName);
          })
        }).catch(()=>{
          this.btnloading = false;
        })
      },

      //下载表格数据格式化
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },
      //去详情页
      toDetail(item){
        let routeData = this.$router.resolve({name:'saleDetail',query:{id:item.orderId}});
        window.open(routeData.href);
      },
      //商品
      remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          this.loading = false;
          goodsList({keywords:query}).then((res)=>{
            this.options = res.list;
          })
        } else {
          this.options = [];
        }
      },

      //获取员工下拉选项
      getUserOptionList(){
        getOrderUsersList({status:1}).then((res)=>{
          this.userOptionList = res;
        })
      },

      //选择员工名称
      handleSelectUserName(key,item){
        this.listQuery[key] = item.userId;
      },

      //客户名称输入匹配
      querySearch(queryString, cb){
        getCustomerOption({keywords:queryString}).then((res)=>{
          cb(res);
        })
      },

      //选择客户名称
      handleSelectCustomerName(item){
        this.listQuery.customerId = item.customerId
      },

      /**
       * 切换选择状态
       */
      handleSelect(key, keyPath){
        this.listQuery.tab = key;
        this.handleSearchList();
      },

      handleSizeChange(val){
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val){
        this.listQuery.pageNum = val;
        this.getList();
      },

      handleSearchList(){
        this.listQuery.pageNum = 1;
        this.getList();
      },

      //获取列表
      getList() {
        this.listLoading = true;
        let fn = invoiceListNew
        if(this.radio1 == 2){
          fn = unInvoiceList
        }
        fn(this.listQuery).then(response => {
          // this.tableData = response.list;
          this.tableData = response.list;
          this.count = response.count;
          if(this.radio1 == 1){
            this.summary = response.summary;
          }else if(this.radio1 == 2){
            this.unInvoiceAmount = response.unInvoiceAmount;
            this.unInvoiceGoodsNum =response.unInvoiceGoodsNum
          }


          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
      },
    },
  }
</script>
